import React, { PureComponent } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { connect } from 'dva'

import {
  Tabs,
  Button,
  Select,
  Table,
  Card,
  message,
  Icon,
  Modal,
  Form,
  Input,
  Upload,
  Popconfirm,
  Radio,
  Divider,
  Badge
} from 'antd'
import { LZFormItem } from '@/components/LZForm'
import commonApi from '@/services/common'
import { uploadUrl } from '@/config'
import { getToken } from '@/utils/localStorage'
import indexServices from './service'

const { TabPane } = Tabs
const { Option } = Select

const nameMap = {
  Banner: 'banner名称',
  icon: '图标名称',
  seal: '腰封名称',
  cube: '豆腐块名称'
}

@connect()
@Form.create()
class IndexSetting extends PureComponent {
  state = {
    loading: false,
    onChannel: '1', // 默认
    newChannel: null,
    pageNumber: 1,
    pageSize: 10,
    total: 10,
    current: 1,
    selectedRowKeys: [],
    addVisible: false, // 控制添加modal的
    title: 'Banner添加', // 添加modal的标题
    fileList: [], // 图片
    imgSrc: '', // 上传成功后的url
    imgVisible: false,
    nameTitle: 'Banner名称',
    tabActiveKey: '1', // tab组件默认激活的
    editVisible: false,
    modalScore: 'add',
    address: 'Banner', // 编辑modal，目标位置的默认值
    name: null,
    url: null,
    sort: null,
    status: null,
    img: null,
    id: null,
    size: 3,
    channelData: [],

    bannerTableData: [],
    sealTableData: [],
    cubeTableData: []
  }

  getColumns = () => {
    const type = this.state.tabActiveKey
    const map = {
      '1': ['Banner', this.deleteBanner],
      '2': ['', () => {}],
      '3': ['腰封', this.deleteSeal],
      '4': ['豆腐块', this.deleteCube]
    }
    const text = map[type][0]
    const fn = map[type][1]
    return [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        align: 'center'
      },
      {
        title: `${text}名称`,
        dataIndex: type === '4' ? 'name' : 'bannerName',
        align: 'center',
        key: type === '4' ? 'name' : 'bannerName'
      },
      {
        title: `${text}图片`,
        dataIndex: type === '4' ? 'imgUrl' : 'imgSrc',
        align: 'center',
        key: type === '4' ? 'imgUrl' : 'imgSrc',
        render: val => <img src={val} alt={val} className="table-cell-img" />
      },
      {
        title: '跳转链接',
        dataIndex: 'jumpUrl',
        align: 'center',
        key: 'jumpUrl'
      },
      {
        title: '上架渠道',
        dataIndex: 'channerNames',
        align: 'center',
        key: 'channerNames',
        render: val => {
          return val && val.join(',')
        }
      },
      {
        title: '上线时间',
        dataIndex: 'createTime',
        align: 'center',
        key: 'createTime'
      },
      {
        title: '状态',
        dataIndex: 'status',
        align: 'center',
        key: 'status',
        render: val => {
          const status = val ? 'success' : 'default'
          const badgeText = val ? '有效' : '失效'
          return <Badge status={status} text={badgeText} />
        }
      },
      {
        title: '排序',
        dataIndex: 'indexSort',
        align: 'center',
        key: 'indexSort'
      },
      {
        title: '操作',
        align: 'center',
        key: 'action',
        render: (val, record) => {
          return (
            <div className="table-action">
              <a onClick={() => this.edit(record)}>修改</a>
              <Divider type="vertical" />
              <Popconfirm title="你确定删除吗?" onConfirm={() => fn(record.id)}>
                <a>删除</a>
              </Popconfirm>
            </div>
          )
        }
      }
    ]
  }

  componentDidMount() {
    this.getBanner()
    this.getChannel()
  }

  // 获取上架渠道信息
  getChannel = () => {
    commonApi.selectPlateformChannel().then(res => {
      this.setState({
        channelData: res
      })
    })
  }

  // 获取banner的数据
  getBanner = () => {
    this.setState(
      {
        loading: true
      },
      () => {
        indexServices
          .getBannerData({
            pageNumber: this.state.pageNumber,
            pageSize: this.state.pageSize
          })
          .then(res => {
            message.success('获取banner信息成功')
            this.setState({
              total: res.total,
              bannerTableData: res.records,
              current: res.current,
              loading: false
            })
          })
      }
    )
  }

  // 删除banner
  deleteBanner = id => {
    indexServices
      .deleteBanner({
        id
      })
      .then(res => {
        message.success('删除成功')
        this.getBanner()
      })
  }

  edit = record => {
    let address

    if (this.state.tabActiveKey === '1') {
      // 表示在banner位置，编辑的时候目标位置，需要显示的
      address = 'Banner'
    } else if (this.state.tabActiveKey === '2') {
      address = 'icon'
    } else if (this.state.tabActiveKey === '3') {
      address = 'seal'
    } else {
      address = 'cube'
    }
    const fileList = [
      {
        uid: 1,
        url: record.imgSrc ? record.imgSrc : record.imgUrl
      }
    ]
    this.setState(
      {
        addVisible: true,
        modalScore: 'edit',
        newChannel: this.state.onChannel,
        address,
        name: record.bannerName
          ? record.bannerName
          : record.iconName
          ? record.iconName
          : record.name,
        url: record.jumpUrl,
        sort: record.indexSort,
        status: record.status,
        size: record.size,
        channelName: record.channerIds,
        img: record.imgSrc ? record.imgSrc : record.imgUrl,
        fileList,
        // 提交用的
        imgSrc: record.imgSrc ? record.imgSrc : record.imgUrl,
        id: record.id
      },
      () => {}
    )
  }

  // 获取腰封
  getSeal = () => {
    this.setState(
      {
        loading: true
      },
      () => {
        // 腰封
        indexServices
          .getSealData({
            pageNumber: this.state.pageNumber,
            pageSize: this.state.pageSize
          })
          .then(res => {
            message.success('获取腰封信息成功')
            this.setState({
              sealTableData: res.records,
              total: res.total,
              current: res.current,
              loading: false
            })
          })
      }
    )
  }

  // 删除腰封
  deleteSeal = id => {
    indexServices.deleteSeal({ id }).then(res => {
      message.success('删除成功')
      this.getSeal()
    })
  }

  // 获取豆腐块
  getCube = () => {
    this.setState(
      {
        loading: true
      },
      () => {
        indexServices
          .getCubeData({
            pageNumber: this.state.pageNumber,
            pageSize: this.state.pageSize
          })
          .then(res => {
            message.success('获取豆腐块信息成功')
            this.setState({
              cubeTableData: res.records,
              total: res.total,
              current: res.current,
              loading: false
            })
          })
      }
    )
  }

  // 删除豆腐块
  deleteCube = id => {
    indexServices.deleteCube({ id }).then(res => {
      message.success('删除成功')
      this.getCube()
    })
  }

  // 切换tans的回调
  onTabChange = key => {
    if (key === '1') {
      // Banner
      this.setState({
        title: 'Banner添加',
        nameTitle: 'Banner名称',
        tabActiveKey: '1',
        address: 'Banner'
      })
    } else if (key === '2') {
      this.setState(
        {
          tabActiveKey: '2',
          title: 'Icon添加',
          nameTitle: '图标名称'
        },
        () => {
          this.getIcon()
        }
      )
    } else if (key === '3') {
      this.setState(
        {
          tabActiveKey: '3',
          title: '腰封添加',
          nameTitle: '腰封名称',
          address: 'seal'
        },
        () => {
          this.getSeal()
        }
      )
    } else {
      // 豆腐块
      this.setState(
        {
          title: '豆腐块添加',
          nameTitle: '豆腐块名称',
          tabActiveKey: '4',
          address: 'cube'
        },
        () => {
          this.getCube()
        }
      )
    }
  }

  handleFilter = () => {
    if (this.state.tabActiveKey === '1') {
      this.getBanner()
    } else if (this.state.tabActiveKey === '2') {
      this.getIcon()
    } else if (this.state.tabActiveKey === '3') {
      this.getSeal()
    } else if (this.state.tabActiveKey === '4') {
    }
  }

  // 分页，下一页
  onChange = pageNumber => {
    this.setState(
      {
        pageNumber
      },
      () => {
        this.handleFilter()
      }
    )
  }

  showTotal = () => {
    return `共有${this.state.total}条`
  }

  // 切换每页数量
  onShowSizeChange = (current, pageSize) => {
    this.setState(
      {
        pageSize,
        pageNumber: 1
      },
      () => {
        this.handleFilter()
      }
    )
  }

  // 新增
  add = () => {
    this.setState({
      addVisible: true,
      newChannel: this.state.onChannel,
      modalScore: 'add',
      name: null,
      url: null,
      sort: null,
      status: null,
      size: 3,
      img: null,
      channelName: []
    })
  }

  renderCubeSize = () => {
    if (this.state.nameTitle !== '豆腐块名称') return null
    const { getFieldDecorator } = this.props.form
    const { size } = this.state
    return (
      <LZFormItem
        label="豆腐块的尺寸"
        field="size"
        requiredMessage="是否生效不能为空"
        getFieldDecorator={getFieldDecorator}
        initialValue={size || null}
      >
        <Radio.Group>
          <Radio value={1}>1(全幅)</Radio>
          <Radio value={2}>1/2</Radio>
          <Radio value={3}>1/3</Radio>
          <Radio value={4}>2/3</Radio>
        </Radio.Group>
      </LZFormItem>
    )
  }

  addressHandleChange = value => {
    this.setState({
      nameTitle: nameMap[value]
    })
  }

  // modal的确认，确认添加和确认更新的
  addOk = () => {
    this.props.form.validateFields((err, value) => {
      value.imgSrc = this.state.imgSrc
      const { size } = this.state
      if (!err) {
        const basePayload = {
          bannerName: value.bannerName,
          name: value.bannerName,
          imgSrc: value.imgSrc,
          indexSort: value.indexSort,
          jumpUrl: value.jumpUrl,
          status: value.status,
          channerIds: value.aa.channel,
          size: value.size ? value.size : size
        }
        if (this.state.modalScore === 'add') {
          // 调用添加的
          if (value.address === 'Banner') {
            // 调用添加banner的接口
            indexServices.addBanner(basePayload).then(res => {
              message.success('添加banner成功')
              this.setState(
                {
                  addVisible: false,
                  fileList: [],
                  tabActiveKey: '1'
                },
                () => {
                  this.props.form.resetFields()
                  this.getBanner()
                }
              )
            })
          } else if (value.address === 'seal') {
            // 调用添加腰封的接口
            indexServices.addSeal(basePayload).then(res => {
              message.success('添加腰封成功')
              this.setState(
                {
                  addVisible: false,
                  fileList: [],
                  tabActiveKey: '3'
                },
                () => {
                  this.props.form.resetFields()
                  this.getSeal()
                }
              )
            })
          } else {
            // 调用添加豆腐块的接口
            basePayload.imgUrl = basePayload.imgSrc
            indexServices.addCube(basePayload).then(res => {
              message.success('添加豆腐块成功')
              this.setState(
                {
                  addVisible: false,
                  fileList: [],
                  tabActiveKey: '4'
                },
                () => {
                  this.props.form.resetFields()
                  this.getCube()
                }
              )
            })
          }
        } else {
          // 调用编辑的
          if (value.address === 'Banner') {
            // 调用更新banner的接口
            indexServices
              .updateBanner({
                id: this.state.id,
                ...basePayload
              })
              .then(res => {
                message.success('编辑成功')
                this.setState(
                  {
                    addVisible: false,
                    fileList: []
                  },
                  () => {
                    this.props.form.resetFields()
                    this.getBanner()
                  }
                )
              })
              .catch(err => {
                message.error(`编辑失败：${err.msg}`)
              })
          } else if (value.address === 'seal') {
            // 调用更新腰封的接口
            indexServices
              .updateSeal({
                id: this.state.id,
                ...basePayload
              })
              .then(res => {
                message.success('编辑成功')
                this.setState(
                  {
                    addVisible: false,
                    fileList: []
                  },
                  () => {
                    this.props.form.resetFields()
                    this.getSeal()
                  }
                )
              })
          } else {
            // 调用更新豆腐块的接口
            basePayload.imgUrl = basePayload.imgSrc
            indexServices
              .updateCube({
                id: this.state.id,
                name: value.bannerName,
                ...basePayload
              })
              .then(res => {
                message.success('编辑成功')
                this.setState(
                  {
                    addVisible: false,
                    fileList: []
                  },
                  () => {
                    this.props.form.resetFields()
                    this.getCube()
                  }
                )
              })
          }
        }
      }
    })
  }

  // 上传的回调
  handleUploadChange = ({ file, fileList, event }) => {
    const filelist = [...fileList] || []
    if (file.status == 'done') {
      filelist.map(item => {
        this.setState({
          imgSrc: item.response.data
        })
      })
    }
    this.setState({
      fileList
    })
  }

  // 上传后预览的回调
  handlePreview = () => {
    this.setState({
      imgVisible: true
    })
  }

  onDownload = () => {
    return window.open(this.state.imgSrc)
  }

  // 上传后删除的回调
  onRemove = () => {
    this.setState(
      {
        fileList: [],
        imgSrc: ''
      },
      () => {}
    )
  }

  render() {
    const {
      loading,
      total,
      current,
      selectedRowKeys,
      addVisible,
      fileList,
      imgVisible,
      imgSrc,
      nameTitle,
      tabActiveKey,
      modalScore,
      address,
      name,
      url,
      sort,
      status,
      img,
      channelData,
      channelName,

      bannerTableData,
      cubeTableData,
      sealTableData
    } = this.state

    const pagination = {
      current,
      total,
      onChange: this.onChange,
      showTotal: this.showTotal,
      showQuickJumper: true,
      pageSizeOptions: ['5', '10', '20'],
      showSizeChanger: true,
      onShowSizeChange: this.onShowSizeChange
    }

    const { getFieldDecorator } = this.props.form
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    )
    return (
      <PageHeaderWrapper title={false} className="index-configure">
        <Card bordered={false}>
          <Tabs
            activeKey={tabActiveKey}
            animated={false}
            onChange={this.onTabChange}
            tabBarExtraContent={
              <div>
                <Button type="primary" onClick={this.add}>
                  新增
                </Button>
              </div>
            }
          >
            <TabPane tab="Banner" key="1">
              <Table
                columns={this.getColumns()}
                loading={loading}
                tableLayout="fixed"
                dataSource={bannerTableData}
                rowKey={record => record.id}
                pagination={pagination}
              />
            </TabPane>
            <TabPane tab="豆腐块" key="4">
              <Table
                columns={this.getColumns()}
                tableLayout="fixed"
                loading={loading}
                dataSource={cubeTableData}
                rowKey={record => record.id}
                pagination={pagination}
              />
            </TabPane>
            <TabPane tab="腰封" key="3">
              <Table
                columns={this.getColumns()}
                loading={loading}
                tableLayout="fixed"
                dataSource={sealTableData}
                rowKey={record => record.id}
                pagination={pagination}
              />
            </TabPane>
          </Tabs>
        </Card>
        <Modal
          title={modalScore === 'add' ? '新增' : '修改'}
          visible={addVisible}
          onCancel={() => {
            this.setState({
              addVisible: false,
              onChannel: this.state.newChannel,
              fileList: []
            })
            this.props.form.resetFields()
          }}
          onOk={this.addOk}
        >
          <Form {...formItemLayout}>
            <Form.Item label="目标位置">
              {getFieldDecorator('address', {
                rules: [
                  {
                    required: true,
                    message: '目标位置不能为空'
                  }
                ],
                initialValue: address || null
              })(
                <Select onChange={this.addressHandleChange} disabled>
                  <Option value="Banner">Banner</Option>
                  {/* <Option value="icon">图标</Option> */}
                  <Option value="seal">腰封</Option>
                  <Option value="cube">豆腐块</Option>
                </Select>
              )}
            </Form.Item>
            {this.renderCubeSize()}
            <Form.Item label={nameTitle}>
              {getFieldDecorator('bannerName', {
                rules: [
                  {
                    required: true,
                    message: `${nameTitle}不能为空`
                  }
                ],
                initialValue: name || null
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label="跳转地址">
              {getFieldDecorator('jumpUrl', {
                rules: [
                  {
                    required: true,
                    message: '跳转地址不能为空'
                  }
                ],
                initialValue: url || null
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label="排序规则">
              {getFieldDecorator('indexSort', {
                rules: [
                  {
                    required: true,
                    message: '排序规则不能为空'
                  }
                ],
                initialValue: sort || null
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label="是否生效">
              {getFieldDecorator('status', {
                initialValue: status === null ? true : status
              })(
                <Radio.Group>
                  <Radio value>生效</Radio>
                  <Radio value={false}>不生效</Radio>
                </Radio.Group>
              )}
            </Form.Item>
            <Form.Item label="上传图片">
              {getFieldDecorator('imgSrc', {
                rules: [
                  {
                    validator: (rule, value, callback) => {
                      const { form } = this.props
                      if (!this.state.imgSrc) {
                        callback('图片不能为空')
                      }
                      callback()
                    }
                  }
                ],
                initialValue: img || null
              })(
                <Upload
                  accept="image/*"
                  action={uploadUrl}
                  headers={{
                    token: getToken()
                  }}
                  listType="picture-card"
                  fileList={fileList}
                  onPreview={this.handlePreview} // 预览
                  onRemove={this.onRemove} // 删除
                  onDownload={this.onDownload}
                  onChange={this.handleUploadChange}
                >
                  {fileList.length >= 1 ? null : uploadButton}
                </Upload>
              )}
            </Form.Item>
            <Form.Item label="上架渠道">
              {getFieldDecorator('aa.channel', {
                rules: [
                  {
                    required: true,
                    message: '上架渠道不能为空'
                  }
                ],
                initialValue: channelName || []
              })(
                <Select
                  mode="multiple"
                  style={{ width: '100%' }}
                  placeholder="请选择上架渠道"
                >
                  {channelData.map((item, sign) => {
                    return (
                      <Option key={item.appId} value={item.channelId}>
                        {' '}
                        {item.channelName}{' '}
                      </Option>
                    )
                  })}
                </Select>
              )}
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          visible={imgVisible}
          footer={null}
          onCancel={() => this.setState({ imgVisible: false })}
          width={600}
        >
          <img
            src={imgSrc || null}
            alt=""
            style={{ width: '100%', paddingTop: 15 }}
          />
        </Modal>
      </PageHeaderWrapper>
    )
  }
}

export default IndexSetting
